package com.living;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import base.common.IInput;
import base.living.Entity;
import base.living.EntityUtil;

public class EntityPlayer extends Entity implements IInput
{
	protected float headRot;
	protected float swingPos;

	private float moveXSpeed;
	private float moveYSpeed;
	private final float moveInc = 0.5F;
	private final float moveFric = 0.25F;
	private final float moveMax = 1F;

	private int prevPosX;
	private int prevPosY;

	public EntityPlayer(int par1, int par2)
	{
		super(par1, par2, 0F, 8);
	}

	@Override
	public void onInputUpdate()
	{
		float mouseRot = (float) EntityUtil.rotToPos(this.posX, this.posY, Mouse.getX(), Mouse.getY());
		this.headRot = (float) EntityUtil.rotToRotWithSpeed(this.headRot, mouseRot, 8, 4);
		this.posRot = (float) EntityUtil.rotToRotWithSpeed(this.posRot, this.headRot, 10, 20);

		if (Keyboard.isKeyDown(Keyboard.KEY_UP) || Keyboard.isKeyDown(Keyboard.KEY_W))
		{
			this.moveYSpeed = this.moveYSpeed < this.moveMax ? this.moveYSpeed + this.moveInc : this.moveMax;
		}
		if (Keyboard.isKeyDown(Keyboard.KEY_DOWN) || Keyboard.isKeyDown(Keyboard.KEY_S))
		{
			this.moveYSpeed = this.moveYSpeed > -this.moveMax ? this.moveYSpeed - this.moveInc : -this.moveMax;
		}
		if (Keyboard.isKeyDown(Keyboard.KEY_LEFT) || Keyboard.isKeyDown(Keyboard.KEY_A))
		{
			this.moveXSpeed = this.moveXSpeed > -this.moveMax ? this.moveXSpeed - this.moveInc : -this.moveMax;
		}
		if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT) || Keyboard.isKeyDown(Keyboard.KEY_D))
		{
			this.moveXSpeed = this.moveXSpeed < this.moveMax ? this.moveXSpeed + this.moveInc : this.moveMax;
		}

		float i = ((int) (this.moveXSpeed * 10));
		float j = ((int) (this.moveYSpeed * 10));

		//Friction
		this.moveXSpeed -= i > 0F ? this.moveFric : i < 0F ? -this.moveFric : 0F;
		this.moveYSpeed -= j > 0F ? this.moveFric : j < 0F ? -this.moveFric : 0F;

		if (!EntityUtil.isCollisionDirectionEmptyOfEntity(this.getWorldObj(), this, i < 0F ? 180F : 0F, (int) this.moveXSpeed))
		{
			this.posX = this.prevPosX;
		}

		if (!EntityUtil.isCollisionDirectionEmptyOfEntity(this.getWorldObj(), this, j < 0F ? 270F : 90F, (int) -this.moveYSpeed))
		{
			this.posY = this.prevPosY;
		}

		if (i != 0F || j != 0F)
		{
			swingPos++;

			if (i != 0F)
			{
				this.prevPosX = this.posX;
				this.posX += Math.round(this.moveXSpeed);
			}

			if (j != 0F)
			{
				this.prevPosY = this.posY;
				this.posY += Math.round(this.moveYSpeed);
			}
		}
		else if (this.getSwingProgress() != 0)
		{
			swingPos++;
		}
	}

	public float getHeadRot()
	{
		return this.headRot;
	}

	public int getSwingProgress()
	{
		return (int) (Math.cos(this.swingPos / 5) * this.boundingBox.width / 3);
	}
}
